package com.teamclub.app.scontrollers

import java.awt.image.BufferedImage
import java.io.IOException

import javax.validation.Valid
import com.fasterxml.jackson.databind.JsonNode
import com.teamclub.app.sforms.AppSubjectUserForm
import com.teamclub.app.sservices.{CaptchaService, LoginService}
import com.teamclub.util.libs.Eithers
import javax.imageio.ImageIO
import javax.servlet.ServletOutputStream
import javax.servlet.http.HttpServletResponse
import org.apache.commons.io.IOUtils
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation._

/**
  * Created by ilkkzm on 17-4-27.
  */
@RestController("com.teamclub.app.scontrollers.LoginController")
@RequestMapping(Array("/"))
class LoginController {
  val logger = LoggerFactory.getLogger(classOf[LoginController])

  @Autowired
  var loginService: LoginService = _

  @Autowired
  var captchaService: CaptchaService = _

  @PostMapping(Array("/app/login"))
  def login(@RequestBody @Valid form: AppSubjectUserForm): JsonNode = {
    Eithers.toJson(loginService.exits(form))
  }

  @GetMapping(Array("captcha.jpg"))
  @throws[IOException]
  def captcha(response: HttpServletResponse, uuid: String): Unit = {
    response.setHeader("Cache-Control", "no-store, no-cache")
    response.setContentType("image/jpeg")
    //获取图片验证码
    val image = captchaService.getCaptcha(uuid)
    val out = response.getOutputStream
    ImageIO.write(image, "jpg", out)
    IOUtils.closeQuietly(out)
  }
}
